﻿using Microsoft.AspNetCore.SignalR;
using System.Timers;

namespace DemoSignalR.Server.Chat
{
    public class TestChatInfo
    {
        private IHubContext<ChatHub> _context;

        private System.Timers.Timer _timer;

        private readonly static object locker = new object();//锁对象

        public static TestChatInfo instance;//当前实例

        private readonly ILogger _logger;

        private int _index = 0;

        private TestChatInfo(IHubContext<ChatHub> _context, ILogger _logger)
        {
            this._context = _context;
            this._logger = _logger;
            //定义定时器
            _timer = new System.Timers.Timer(100);
            _timer.AutoReset = true;
            _timer.Enabled = true;
            _timer.Elapsed += Timer_Elapsed;
            _timer.Start();
        }

        private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            //业务逻辑判断
            var obj = new TestValue();
            obj.Index = this._index;
            obj.Value = DateTime.Now.Millisecond % 100;
            _context.Clients.All.SendAsync("RefreshInfos", obj);
            this._index++;
        }

        /// <summary>
        /// 注册，即初始化单例实例
        /// </summary>
        /// <param name="context"></param>
        /// <param name="reviewTaskService"></param>
        /// <param name="sysParamService"></param>
        public static void Register(IHubContext<ChatHub> context, ILogger logger)
        {
            lock (locker)
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        instance = new TestChatInfo(context, logger);
                    }
                }
            }
        }

    }

    public class TestValue
    {
        private int index;
        public int Index { get { return index; } set { index = value; } }

        private float value;
        public float Value { get { return value; } set { this.value = value; } }
    }
}
